package com.taomu.app.zongchouhuli.framework;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.taomu.app.zongchouhuli.R;

import java.lang.reflect.InvocationTargetException;

/**
 * 通用webview
 */
public class CommonWebActivity extends BaseActivity{

    private WebView mRichDetailWebView;

    private TextView mTitleTv;

    private ImageView mBackIm;

    private FrameLayout mFrameLayout;

    private ProgressBar mProgressBar;

    public static final String COMMONWEBURL = "commonurl";

    public static final String COMMONWEBCONTENT = "commoncontent";

    public static final String COMMONWEBISCONTENT = "iscontent";

    public static final String COMMONWEBTITLE = "commonwebtitle";

    private boolean m_IsLoadResource = false;

    private boolean isContent = false;

    private String mCommonUrl = "";

    private String mCommonContent = "";

    private String mTitle = "";

    public static void startWithContent(Context mContext,String content, String title){
        Intent intent = new Intent(mContext,CommonWebActivity.class);
        intent.putExtra(COMMONWEBCONTENT,content);
        intent.putExtra(COMMONWEBISCONTENT,true);
        intent.putExtra(COMMONWEBTITLE,title);
        mContext.startActivity(intent);
    }

    public static void startWithUrl(Context mContext,String url,String title){
        Intent intent = new Intent(mContext,CommonWebActivity.class);
        intent.putExtra(COMMONWEBURL,url);
        intent.putExtra(COMMONWEBISCONTENT,false);
        intent.putExtra(COMMONWEBTITLE,title);
        mContext.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        mRichDetailWebView.stopLoading();
        mRichDetailWebView.getSettings().setJavaScriptEnabled(false);
        mRichDetailWebView.clearHistory();
        mRichDetailWebView.removeAllViews();
        mRichDetailWebView.destroy();
        super.onDestroy();
    }

    @Override
    protected int getContentLayout() {
        return R.layout.common_web;
    }

    @Override
    protected void initView() {
        mBackIm = findViewById(R.id.web_back_im);
        mTitleTv = findViewById(R.id.web_title_tv);
        mRichDetailWebView = findViewById(R.id.common_web_webview);
        mFrameLayout = findViewById(R.id.common_error_frame);
        mProgressBar = findViewById(R.id.common_progress_bar);
        settingWeb();
    }

    @Override
    protected void initData() {
        getBaseInfo();
        if(!TextUtils.isEmpty(mTitle)){
            mTitleTv.setText(mTitle);
        }
        loadUrl();
    }

    @Override
    protected void initEvent() {
        mBackIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mRichDetailWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if(newProgress<=99){
                    if(mProgressBar.getVisibility() != View.VISIBLE){
                        mProgressBar.setVisibility(View.VISIBLE);
                    }
                    mProgressBar.setProgress(newProgress);
                }else{
                    mProgressBar.setVisibility(View.GONE);
                }
            }

        });

        mRichDetailWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
//				m_IsLoadResource = false;
                mProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(final WebView view, String url) {
                super.onPageFinished(view, url);
                mProgressBar.setVisibility(View.GONE);
            }

            @Override
            public void onLoadResource(WebView view, String url) {

                m_IsLoadResource = true;
                super.onLoadResource(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description,
                                        String failingUrl) {

                view.stopLoading();
                if(!m_IsLoadResource) {
                    //展示错误界面
                    mFrameLayout.setVisibility(View.VISIBLE);
                }
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
        mFrameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFrameLayout.setVisibility(View.GONE);

            }
        });
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    private void settingWeb(){
        mRichDetailWebView.clearCache(true);
        mRichDetailWebView.reload();
        //mRichDetailWebView.addJavascriptInterface(new JsScript(getUsualFragment(),mRichDetailWebView),"NativeObject");
        //去掉滚动条
        mRichDetailWebView.setHorizontalScrollBarEnabled(false);//水平不显示
        mRichDetailWebView.setVerticalScrollBarEnabled(false); //垂直不显示
        //DOM
        mRichDetailWebView.getSettings().setDomStorageEnabled(true);
        //如果打不开网页设置一下两个
        mRichDetailWebView.getSettings().setAppCacheEnabled(true);
        mRichDetailWebView.getSettings().setAllowFileAccess(true);
        mRichDetailWebView.getSettings().setAllowContentAccess(true);
        //设置  Application Caches 缓存目录
        mRichDetailWebView.getSettings().setDatabaseEnabled(true);
        mRichDetailWebView.getSettings().setSavePassword(true);
        mRichDetailWebView.getSettings().setSaveFormData(true);
        //设置数据库缓存路径
        //设置缓冲大小，我设的是8M
        mRichDetailWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        mRichDetailWebView.getSettings().setLoadsImagesAutomatically(true);
        //允许JavaScript
        mRichDetailWebView.getSettings().setJavaScriptEnabled(true);
        mRichDetailWebView.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
        //解决超出屏幕问题
        mRichDetailWebView.getSettings().setLoadWithOverviewMode(true);
        try {
            mRichDetailWebView.getSettings().getClass().getMethod("setPageCacheCapacity", Integer.TYPE).invoke(mRichDetailWebView.getSettings(), 5);
            mRichDetailWebView.getSettings().setSupportMultipleWindows(true);
            mRichDetailWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= 16) {
            mRichDetailWebView.getSettings().setAllowFileAccessFromFileURLs(true);
            mRichDetailWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }
        //添加事件
        mRichDetailWebView.getSettings().setBuiltInZoomControls(true);
        //去掉缩放按钮，就是加减号
        mRichDetailWebView.getSettings().setDisplayZoomControls(false);
        //适应分辨率
        mRichDetailWebView.getSettings().setUseWideViewPort(true);
        //设置缓存模式
        mRichDetailWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    private void getBaseInfo(){
        if(getIntent() != null){
            isContent = getIntent().getBooleanExtra(COMMONWEBISCONTENT,false);
            mCommonContent = getIntent().getStringExtra(COMMONWEBCONTENT);
            mCommonUrl = getIntent().getStringExtra(COMMONWEBURL);
            mTitle = getIntent().getStringExtra(COMMONWEBTITLE);
        }
    }

    private void loadUrl(){
        if(isContent) {
            mRichDetailWebView.loadData(mCommonContent, "text/html; charset=UTF-8", null);
        }else{
            mRichDetailWebView.loadUrl(mCommonUrl);
        }
    }
}
